package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.exception.BusinessException;
import com.graduation.springbootinit.mapper.GiftMapper;
import com.graduation.springbootinit.model.entity.ActivityPart.Gift;
import com.graduation.springbootinit.model.entity.ActivityPart.ExchangeRecord;
import com.graduation.springbootinit.service.ExchangeRecordService;
import com.graduation.springbootinit.service.GiftService;
import com.graduation.springbootinit.service.UserPointsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class GiftServiceImpl extends ServiceImpl<GiftMapper, Gift>
        implements GiftService {

    @Resource
    private UserPointsService userPointsService;
    
    @Resource
    private ExchangeRecordService exchangeRecordService;

    @Override
    public void createGift(Gift gift) {
        // 验证参数
        if (gift.getName() == null || gift.getName().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "礼品名称不能为空");
        }
        if (gift.getPoints() == null || gift.getPoints() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "兑换积分必须大于0");
        }
        if (gift.getStock() == null || gift.getStock() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "库存不能为负数");
        }
        
        // 设置默认值
        if (gift.getStatus() == null) {
            gift.setStatus(1); // 默认上架
        }
        
        save(gift);
    }

    @Override
    public Page<Gift> listGifts(int pageNum, int pageSize) {
        QueryWrapper<Gift> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1) // 只查询上架的礼品
                .orderByDesc("created_at");
        return page(new Page<>(pageNum, pageSize), queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exchangeGift(Long userId, Long giftId, Long addressId) {
        // 获取礼品信息
        Gift gift = getById(giftId);
        if (gift == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "礼品不存在");
        }
        if (gift.getStatus() != 1) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "礼品已下架");
        }
        
        // 检查库存
        if (!checkStock(giftId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "库存不足");
        }
        
        // 扣减积分
        boolean success = userPointsService.deductPoints(userId, gift.getPoints(), 
                "兑换礼品：" + gift.getName());
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "积分不足");
        }
        
        // 创建兑换记录
        ExchangeRecord record = new ExchangeRecord();
        record.setUserId(userId);
        record.setGiftId(giftId);
        record.setAddressId(addressId);
        record.setPointsCost(gift.getPoints());
        record.setStatus(0); // 待发货
        exchangeRecordService.save(record);
        
        // 减少库存
        decreaseStock(giftId);
    }

    @Override
    public Page<ExchangeRecord> getUserExchangeRecords(Long userId, int pageNum, int pageSize) {
        return exchangeRecordService.getUserExchangeRecords(userId, pageNum, pageSize);
    }

    @Override
    public void updateExchangeStatus(Long recordId, Integer status) {
        exchangeRecordService.updateStatus(recordId, status);
    }

    @Override
    public boolean checkStock(Long giftId) {
        Gift gift = getById(giftId);
        return gift != null && gift.getStock() > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void decreaseStock(Long giftId) {
        baseMapper.decreaseStock(giftId);
    }
} 